<?php
declare(strict_types=1);
namespace Cache;
use Config;
use JetBrains\PhpStorm\NoReturn;
use RedisException;

class Redis
{
    /**
     * 静态实例
     * @var \Redis|null
     */
    private static ?\Redis $_instance = null;

    /**
     * @param int|null $dbNum
     * @throws RedisException
     */
    #[NoReturn]
    private function __construct(?int $dbNum = null){ //私有的构造方法
        self::$_instance = new \Redis();
        $config = Config::get("redis");
        self::$_instance->connect($config['host'],(int)$config['port']);
        if(isset($config['password']))self::$_instance->auth($config['password']);
        self::$_instance->select($dbNum?:(int)$config['database']);
        self::$_instance->setOption(\Redis::OPT_SERIALIZER, \Redis::SERIALIZER_PHP);
        self::$_instance->getOption(\Redis::OPT_SERIALIZER);
    }

    /**
     * 获取静态实例
     * @param int|null $db redis库
     * @return \Redis|null
     * @throws RedisException
     */
    public static function getRedis(?int $db = null): ?\Redis
    {
        if(!self::$_instance) new self($db);
        return self::$_instance;
    }

    private function __clone(){}
}
